<template>
  <a-spin :spinning="loading" tip="加载中">
    <div class="h-566 overflow-y-auto">
      <a-timeline class="p-10" style="min-height: 400px" mode="left">
        <a-timeline-item v-for="groupItem in lifeList" :key="groupItem.operationGroupTime">
          <template #dot><i class="iconfont icon-time-fill"></i></template>
          <a-space direction="vertical" :size="20" style="width: 100%">
            <span> {{ groupItem.operationGroupTime }}</span>
            <div v-for="lifeItem in groupItem.lifeCycleList" :key="lifeItem.id" class="item">
              <div class="date-time">
                <span class="mr-8">{{ dayjs(lifeItem.operationTime).format('YYYY-MM-DD') }}</span>
                <span>{{ dayjs(lifeItem.operationTime).format('HH:mm:ss') }}</span>
              </div>
              <div class="content">{{ lifeItem.content }}</div>
              <a-button v-if="lifeItem.type !== 1" type="link" class="mx-16" @click="checkLifecycle(lifeItem)">查看</a-button>
              <a-button v-else-if="lifeItem.type == 1 && lifeItem.remark" type="link" class="mx-16" @click="checkReason(lifeItem.remark)">
                查看
              </a-button>
            </div>
          </a-space>
        </a-timeline-item>
        <a-timeline-item />
      </a-timeline>
    </div>
  </a-spin>

  <!-- 详情弹窗 -->
  <a-modal
    centered
    title="详情"
    width="936px"
    height="506px"
    :body-style="{ minHeight: '500px' }"
    :open="previewState.visibleModal"
    :footer="false"
    @cancel="previewCancel"
  >
    <a-table
      v-if="accreditData.recordType === 1"
      :columns="onlineTableColumns"
      :data-source="accreditData.changeItemList"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'onlineService'">
          {{ `${accreditData.onlineId}_${accreditData.algoName}_${accreditData.version}` }}
        </template>
        <template v-else-if="column.dataIndex === 'onlineChange'">
          <div class="elliptical-1" :title="`${record.name} ${record.oldValue} → ${record.newValue}`">
            <span style="margin-right: 15px"> {{ record.name }}</span>
            <span style="margin-right: 5px"> {{ record.oldValue }}</span>
            <i>→</i>
            <span style="margin-left: 5px"> {{ record.newValue }}</span>
          </div>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template></a-table
    >

    <a-table
      v-else-if="accreditData.recordType === 2"
      :style="{ width: '100%' }"
      :columns="serialNumTableColumns"
      :data-source="accreditData.changeItemList"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'serialNumService'">
          {{
            `${accreditData.serialNum}_${accreditData.algoName}_${accreditData.version}_${accreditData.platform}_${accreditData.language}`
          }}
        </template>
        <template v-else-if="column.dataIndex === 'serialNumChange'">
          <div class="elliptical-1" :title="`${record.name} ${record.oldValue} → ${record.newValue}`">
            <span style="margin-right: 15px"> {{ record.name }}</span>
            <span style="margin-right: 5px"> {{ record.oldValue }}</span>
            <i>→</i>
            <span style="margin-left: 5px"> {{ record.newValue }}</span>
          </div>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template></a-table
    >
    <a-table
      v-else-if="accreditData.recordType === 3"
      :style="{ width: '100%' }"
      :columns="licenseTableColumns"
      :data-source="accreditData.changeItemList"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'licenseService'">
          {{
            `${accreditData.licenseId}_${accreditData.algoName}_${accreditData.version}_${accreditData.platform}_${accreditData.language}`
          }}
        </template>
        <template v-else-if="column.dataIndex === 'licenseChange'">
          <div class="download">
            <div class="download-item">
              <span style="margin-right: 15px"> {{ record.name }}</span>
              <div class="elliptical-1">
                <a
                  class="downloadFileName"
                  :title="`${record.oldValue}`"
                  @click.stop="previewFingerprint(record.oldValue, record.oldFileUrl)"
                >
                  {{ record.oldValue }}
                </a>
              </div>

              <i class="ml-5 cursor-pointer icon-download-2-line iconfont" @click.stop="downloadFingerprint(record.oldAuditId)"></i>
            </div>
            <div class="download-item">
              <i class="iconSy">→</i>
              <div class="elliptical-1">
                <a
                  class="downloadFileName"
                  :title="`${record.newValue}`"
                  @click.stop="previewFingerprint(record.newValue, record.newFileUrl)"
                >
                  {{ record.newValue }}</a
                >
              </div>
              <i class="ml-5 cursor-pointer icon-download-2-line iconfont" @click.stop="downloadFingerprint(record.newAuditId)"></i>
            </div>
          </div>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template></a-table
    >
    <div v-else><a-table /></div>
  </a-modal>
  <!-- 预览指纹文件 -->
  <a-modal
    :open="previewVisible"
    :footer="null"
    width="988px"
    :body-style="{ background: '#F2F2F5', borderRadius: '4px' }"
    @cancel="handleCancel"
  >
    <template #title>
      <div class="modalTitle" :title="previewTitle">{{ previewTitle }}</div>
    </template>
    <div class="example">
      <a-spin :spinning="loadingShow" tip="加载中">
        <p class="preview-text">{{ previewTxt }}</p>
      </a-spin>
    </div>
  </a-modal>

  <!-- 驳回理由弹窗 -->
  <a-modal
    centered
    title="理由"
    width="416px"
    :body-style="{ minHeight: '88px', borderRadius: '4px' }"
    :open="rejectState.visibleModal"
    :footer="false"
    @cancel="rejectCancel"
  >
    <div>
      <p class="preview-text">{{ rejectTxt }}</p>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import dayjs from 'dayjs'
  import { inject, reactive, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import { clientApi } from '@/services/api'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'

  import { downloadFingerprint } from '../../../utils/download'

  export interface Datum {
    lifeCycleList?: LifeCycleList[]
    operationGroupTime?: string
  }

  export interface LifeCycleList {
    content?: string
    id?: number
    operationTime?: string
    /**
     * 备注
     */
    remark: string
    /**
     * (1, "公共"),
     * (2, "创建/编辑授权应用")
     * (3, "审核应用")
     * (4, "删除应用")
     * (5, "管理员授权服务")
     */
    type?: number
    uid?: number
    rid: string
  }
  interface PreviewState {
    visibleModal: boolean
  }

  const clientId = inject('clientId') as string
  const lifeList = ref<Datum[]>([])

  const accreditData = ref<any>({})
  // 表格
  const onlineTableColumns = ref(
    filterTableColumns([
      {
        title: '在线服务',
        dataIndex: 'onlineService'
      },
      {
        title: '变更项',
        dataIndex: 'onlineChange'
      }
    ])
  )
  const licenseTableColumns = ref(
    filterTableColumns([
      {
        title: 'license',
        dataIndex: 'licenseService'
      },
      {
        title: '变更项',
        dataIndex: 'licenseChange'
      }
    ])
  )
  const serialNumTableColumns = ref(
    filterTableColumns([
      {
        title: '序列号',
        dataIndex: 'serialNumService'
      },
      {
        title: '变更项',
        dataIndex: 'serialNumChange'
      }
    ])
  )

  const { loading, runAsync: getLifeInfo } = useRequest<ResponseData<any>>(clientApi.lifeDetail(clientId), {
    onSuccess: res => {
      const { data } = res
      Object.assign(lifeList.value, data)
    },
    onError: () => {}
  })

  const checkLifecycle = async (item: LifeCycleList) => {
    const lifecycleApis = {
      2: clientApi.lifecycleDetailsType2,
      3: clientApi.lifecycleDetailsType3,
      4: clientApi.lifecycleDetailsType4,
      5: clientApi.lifecycleDetailsType5
    } as any

    const api = lifecycleApis[`${item.type}`]

    if (api) {
      if (item.type === 2) {
        window.open(`/user-manage/life/app-check-app-detail/${item.rid}`)
      } else if (item.type === 3) {
        window.open(`/user-manage/life/app-check-detail/${item.rid}`)
      } else if (item.type === 4) {
        window.open(`/user-manage/life/app-detail/${item.rid}`)
      } else if (item.type === 5) {
        const { data } = await api(item.rid)()
        Object.assign(accreditData.value, data)
        previewState.visibleModal = true
      }
    }
  }

  const rejectTxt = ref<string>('')
  const checkReason = (reason: string) => {
    console.log(reason, 'reason')
    rejectState.visibleModal = true
    rejectTxt.value = reason
  }
  const previewState = reactive<PreviewState>({
    visibleModal: false
  })
  const previewCancel = () => {
    previewState.visibleModal = false
  }
  const rejectState = reactive<PreviewState>({
    visibleModal: false
  })
  const rejectCancel = () => {
    rejectState.visibleModal = false
    rejectTxt.value = ''
  }

  /* 预览指纹文件-------------------------------------------------------------------------------------------------------- */
  const previewVisible = ref<boolean>(false)
  const previewTitle = ref<string>('')
  const previewTxt = ref<string>('')
  const loadingShow = ref<boolean>(false)

  //预览指纹文件
  const previewFingerprint = async (fileName: string, fileUrl: string): Promise<void> => {
    loadingShow.value = true
    previewTitle.value = fileName
    previewVisible.value = true

    fetch(fileUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error()
        }
        return response.text()
      })
      .then(text => {
        previewTxt.value = text
        loadingShow.value = false
      })
      .catch(error => {
        loadingShow.value = false
        console.error('Error downloading text:', error)
      })
  }

  const handleCancel = () => {
    previewVisible.value = false
    previewTitle.value = ''
    previewTxt.value = ''
  }
  /* ------------------------------------------------------------------------------------------------------------------- */

  getLifeInfo()
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .icon-time-fill {
    color: rgba(3, 42, 105, 0.45);
  }

  :deep(.ant-timeline) {
    .ant-timeline-item-head-blue {
      display: none;
    }

    .ant-timeline-item-head-custom {
      display: inline-block;
    }

    .ant-timeline-item {
      padding-bottom: 0;
    }

    .ant-timeline-item-tail {
      height: calc(100% - 17px);
    }
  }

  .item {
    display: flex;
    align-items: center;
    padding: 20px 0;
    color: @text01;
    background: @background2;
    border: 1px solid @border1;
    border-radius: 6px;
    align-self: stretch;

    .date-time {
      padding: 0 20px;
      min-width: 173px;
      border-right: 2px solid rgba(0, 0, 0, 0.05);

      > span:nth-of-type(2) {
        color: @text03;
      }
    }

    .content {
      padding-left: 20px;
    }
  }

  .download {
    display: flex;
    height: 98px;
    flex-direction: column;

    .download-item {
      display: flex;
      align-items: center;
      height: 50%;
    }

    .downloadFileName {
      text-decoration: underline;
      color: #009cf8;
    }

    .iconfont {
      color: #009cf8;
    }

    .iconSy {
      margin-right: 14px;
    }

    .block {
      display: block;
    }
  }

  .example {
    text-align: center;
    border-radius: 4px;

    .preview-text {
      overflow-y: auto;
      padding: 0 0 0 15px;
      height: 700px;
      text-align: left;
      white-space: pre-wrap;
    }
  }

  .modalTitle {
    overflow: hidden;
    width: 930px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :deep(.ant-modal-content) {
    padding: 6px;
    border-radius: 4px;
  }
</style>
